package com.zhoutao.blog.seven.dao.repository;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.zhoutao.blog.seven.dao.mapper.ArticleMapper;
import com.zhoutao.blog.seven.dao.model.ArticleDao;
import com.zhoutao.blog.seven.dao.model.TupleDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Service
public class ArticleRepository extends ServiceImpl<ArticleMapper, ArticleDao> {

    public IPage<ArticleDao> all(
            Optional<Long> categoryId,
            Optional<Long> tagId,
            Optional<String> type,
            Integer page, Integer limit) {
        IPage<ArticleDao> pageInfo = new Page<>(page, limit);
        return this.baseMapper.find(pageInfo, categoryId.orElse(null), tagId.orElse(null), type.orElse(null));
    }

    public void addReadCount(Long id) {
        this.baseMapper.addReadCount(id);
    }

    /**
     * 按目录分组统计文章数量
     *
     * @param categoryIds
     * @return
     */
    public Map<Long, Long> count(List<Long> categoryIds) {
        if (CollectionUtils.isEmpty(categoryIds)) {
            return Collections.emptyMap();
        }
        List<TupleDao<Long, Long>> countList = this.baseMapper.count(categoryIds);
        Map<Long, Long> countMap = Maps.newHashMap();
        for (TupleDao<Long, Long> tupleDao : countList) {
            countMap.put(tupleDao.getKey(), tupleDao.getValue());
        }
        return countMap;
    }

    public void updateCommentCount(Long id) {
        this.baseMapper.addCommentCount(id);
    }
}
